import { reactive, ref } from 'vue'
import { TypeLogin, loginRules } from '@/types/typeData'
import useStore from '@/stores/index'
import type { FormInstance } from 'element-plus'

export default function loginFn() {
  const { user } = useStore()
  // 获取验证码
  user.getCode()
  // 登录loading
  const loading = ref<boolean>(false)
  // 账号密码
  const loginForm = reactive<TypeLogin>({
    account: 'shenlingadmin',
    password: '123456',
    code: '',
    key: 'E40C3B489D1793C2FC8074751677827045549',
  })
  const form = ref<FormInstance>()
  // 校验
  const rules = reactive<loginRules>({
    account: [{ required: true, message: '不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '不能为空', trigger: 'blur' }],
  })
  // 登录
  const login = async (formEl: FormInstance | undefined) => {
    if (formEl) {
      await formEl.validate()
      loading.value = true
      await user.login(loginForm)
      loading.value = false
    }
  }
  return { loading, user, loginForm, form, rules, login }
}
